﻿package app.view.components.sections.expo 
{
	import app.model.Qubix;
	import app.model.types.LangTypes;
	import app.view.components.buttons.GlamurBtnBase;
	import app.view.components.buttons.LangBtn;
	import app.view.components.guiDima.keyboard.KeyBoardDBase;
	import app.view.components.guiDima.keyboard.KeyBoardWithInputFieldDBase;
	import app.view.components.guiDima.sky.InputSkyDBase;
	import app.view.components.guiDima.sky.SkyFieldDBase;
	import app.view.components.guiDima.sky.SkyMesageDBase;
	import app.view.components.sections.LabeledSectionBase;
	import app.view.events.KeyboardEventD;
	import flash.display.Sprite;
	import flash.events.MouseEvent;
	import flash.net.NetConnection;
	import flash.net.Responder;
	import flash.utils.setTimeout;
	import gs.TweenLite;
	
	/**
	 * 1.4.2 ОСТАВИТЬ ОТЗЫВ
	 * @author Dmitryi_Koruagin, icq:585466579, dmitryikoruagin@mail.ru, skype: ok_ru1
	 */
	public class ExpoFeedBacksWriteDBase extends LabeledSectionBase
	{
		// app.view.components.sections.expo.ExpoFeedBacksWriteDBase
		//public var board:KeyBoardWithInputFieldDBase;
		public var board:KeyBoardDBase;
		public var inputSky:InputSkyDBase;
		
		
		
		public var bgd:Sprite;
		public var sendBTN:GlamurBtnBase;
		public var clearBTN:GlamurBtnBase;
		public var echeBtn:GlamurBtnBase;
		
		public var spasibo:LangBtn;
		
		public var skyField:SkyFieldDBase;
		
		public var messageSky:SkyMesageDBase;
		
		private var _currentText:String;
		
		private var _timeOutDelay:int;
		
		private static const INPUT_SKY_FIRST_X:Number = 900;
		private static const INPUT_SKY_FIRST_Y:Number = 220;
		
		// для отправки сообщения
		private var connection:NetConnection;
		private var loginResponder:Responder;
		private var messageResponder:Responder;
		private var _currentMessage:String = '';
		private var _currentName:String='EXPO 2010';
		
		
		public function ExpoFeedBacksWriteDBase() 
		{
			super();
			
			sendBTN.alpha = 0;
			sendBTN.mouseChildren = false;
			sendBTN.mouseEnabled = false;
			clearBTN.alpha = 0;
			clearBTN.mouseChildren = false;
			clearBTN.mouseEnabled = false;
			echeBtn.alpha = 0;
			echeBtn.mouseChildren = false;
			echeBtn.mouseEnabled = false;
			
			spasibo.alpha = 0;
			spasibo.mouseChildren = false;
			spasibo.mouseEnabled = false;
			
			//inputSky.mouseChildren = false;
			//inputSky.mouseEnabled = false;
		}
		
		private function showSpasibo():void
		{
			TweenLite.to(spasibo, 0.5, { alpha: 1 , ease:'none' } );
		}
		private function hideSpasibo():void
		{
			TweenLite.to(spasibo, 0.5, { alpha: 0 ,ease:'none'} );
		}
		
		private function setEvents():void
		{
			bgd.mouseChildren = false;
			bgd.mouseEnabled = false;
			
			addEventListener(KeyboardEventD.ON_INPUT_TEXT, onInputText, true);
			addEventListener(KeyboardEventD.ON_KEY_BACKSPACE, onKeyBackSpace, true);
			addEventListener(KeyboardEventD.ON_KEY_ENTER, onKeyEnter, true);
			addEventListener(KeyboardEventD.ON_CLICK_SKY_MESSAGE, onClickMessage, true);
			addEventListener(KeyboardEventD.ON_KEY_LEFT, onKeyLeft, true);
			addEventListener(KeyboardEventD.ON_KEY_RIGHT, onKeyRight, true);
			//addEventListener(KeyboardEventD.ON_CHANGE_BOARD_LANG, onChangeBoardLang, true);
			sendBTN.addEventListener(MouseEvent.CLICK, onCLickSendBtn);
			clearBTN.addEventListener(MouseEvent.CLICK, onClickClearBtn);
		}
		
		private function setLang(e:KeyboardEventD):void 
		{
			
			////trace('lang+++---',board.currentLang);
			spasibo.setLang(board.currentLang);
			inputSky.setLang(board.currentLang);
			
		}
		
		
		private function removeEvents():void
		{
			bgd.mouseChildren = true;
			bgd.mouseEnabled = true;
			removeEventListener(KeyboardEventD.ON_INPUT_TEXT, onInputText, true);
			removeEventListener(KeyboardEventD.ON_KEY_BACKSPACE, onKeyBackSpace, true);
			removeEventListener(KeyboardEventD.ON_KEY_ENTER, onKeyEnter, true);
			removeEventListener(KeyboardEventD.ON_CLOSE_SKY_MESSAGE, onClosekMessage, true);
			removeEventListener(KeyboardEventD.ON_KEY_LEFT, onKeyLeft, true);
			removeEventListener(KeyboardEventD.ON_KEY_RIGHT, onKeyRight, true);
			sendBTN.removeEventListener(MouseEvent.CLICK, onCLickSendBtn);
			clearBTN.removeEventListener(MouseEvent.CLICK, onClickClearBtn);
		}
		
		override public function onDestroy():void 
		{
			// чистим что тут есть и вызываем супера
			removeEvents();
			echeBtn.removeEventListener(MouseEvent.CLICK, onAddSkyMessage);
			removeEventListener(KeyboardEventD.ON_CLICK_SKY_MESSAGE, onClickMessage, true);
			
			skyField.destroy();
			messageSky.destroy();
			board.destroy();
			inputSky.destroy();
			sendBTN.destroy();
			clearBTN.destroy();
			echeBtn.destroy();
			
			super.onDestroy();
		};
		
		override public function get data():Object { return _data; };
		
		override public function set data(value:Object):void 
		{
			super.data = value;
			
			
			setEvents();
			
			inputSky.setLang(_data.lang);
			inputSky.currentValue = '';
			skyField.startTweenMove();
			
			//trace('data PAGE_EXPO_FEEDBACK_WRITE', _data.lang);
			
			//for (var name:String in _data.data) 
			//{
				//trace('name = ', name);
			//}
			
			var lan:String = _data.lang;
			lan == LangTypes.CHINA ? lan = LangTypes.ENGLISH : 0;
			
			
			board.setFirstParam(lan);
			sendBTN.setLang(_data.lang);
			clearBTN.setLang(_data.lang);
			echeBtn.setLang(_data.lang);
			spasibo.setLang(_data.lang);
			
		};
		
		/**
		 * нажали энтер
		 * @param	e
		 */
		private function onKeyEnter(e:KeyboardEventD):void 
		{
			currentText = String(inputSky.currentValue + '\n');
			
			inputSky.positionCursor = _currentText.length;
		}
		
		/**
		 * нажали бекспейс
		 * @param	e
		 */
		private function onKeyBackSpace(e:KeyboardEventD):void 
		{
			//trace('111',currentText,_currentText.slice());
			var sl:String = _currentText;
			var sr:String = _currentText;
			
			if (currentText!='') 
			{
				
				currentText = sl.slice(0, inputSky.currentPositionCursor - 1) + sr.slice(inputSky.currentPositionCursor, currentText.length);
				
				inputSky.positionCursor = inputSky.currentPositionCursor - 1;
				
			}else
			{
				
			}
			
			
			////trace('222',currentText);
		}
		
		/**
		 * ввод текста
		 * @param	e
		 */
		private function onInputText(e:KeyboardEventD):void 
		{
			trace('***',e.str);
			currentText = String(inputSky.currentValue + e.str);
			
			//trace('444',inputSky.currentPositionCursor, sp);
			inputSky.positionCursor = inputSky.currentPositionCursor + e.str.length;
		}
		
		public function get currentText():String { return inputSky.currentValue; }
		
		public function set currentText(value:String):void 
		{
			//trace('+++',_currentText);
			
			//var sp:int = value.length;
			
			if (value.length>InputSkyDBase.MAX_CHAIR) 
			{
				
				board.blockAllKeyWithoutBackSpace();
				inputSky.positionCursor = InputSkyDBase.MAX_CHAIR;
			}else
			{
				board.unBlockAllKey();
				
				_currentText = value;
				inputSky.currentValue = _currentText;
				
				if (_currentText!='') 
				{
					TweenLite.to(sendBTN, 0.5, { alpha: 1 ,ease:'none'} );
					sendBTN.mouseChildren = true;
					sendBTN.mouseEnabled = true;
					TweenLite.to(clearBTN, 0.5, { alpha: 1 ,ease:'none'} );
					clearBTN.mouseChildren = true;
					clearBTN.mouseEnabled = true;
					
					//trace('333', inputSky.currentValue.length);
					
					
				}else 
				{
					TweenLite.to(sendBTN, 0.5, { alpha: 0 ,ease:'none'} );
					sendBTN.mouseChildren = false;
					sendBTN.mouseEnabled = false;
					TweenLite.to(clearBTN, 0.5, { alpha: 0 ,ease:'none'} );
					clearBTN.mouseChildren = false;
					clearBTN.mouseEnabled = false;
				}
				
				
				
			}
			
		}
		
		private function onClickMessage(e:KeyboardEventD):void 
		{
			removeEvents();
			addEventListener(KeyboardEventD.ON_CLOSE_SKY_MESSAGE, onClosekMessage, true);
			
			
			
			
			messageSky.currentValue = e.str;
			
			
			TweenLite.to(messageSky, 2, {delay:3, y: 500, alpha: 1 , ease:'none' } );
			
			bgd.addEventListener(MouseEvent.CLICK, onCloseMess);
		}
		
		private function onCloseMess(e:MouseEvent):void 
		{
			setEvents();
			TweenLite.to(messageSky, 2, { y: -400, alpha: 0 , ease:'none' } );
		}
		
		private function onClosekMessage(e:KeyboardEventD):void 
		{
			setEvents();
			TweenLite.to(messageSky, 2, { y: -400, alpha: 0 , ease:'none' } );
		}
		
		private function onCLickSendBtn(e:MouseEvent):void 
		{
			if (inputSky.currentValue != '') 
			{
				
				removeEvents();
				// нужно отправить сообщение кубику на модерацию и облачко должно улететь и появиться
				//inputSky.hide(0.5);
				
				board.mouseChildren = false;
				board.mouseEnabled = false;
				
				
				TweenLite.to(sendBTN, 0.5, { alpha: 0 ,ease:'none'} );
				sendBTN.mouseChildren = false;
				sendBTN.mouseEnabled = false;
				TweenLite.to(clearBTN, 0.5, { alpha: 0 ,ease:'none'} );
				clearBTN.mouseChildren = false;
				clearBTN.mouseEnabled = false;
				
				
				_timeOutDelay = setTimeout(showMark, 1000);
				
				_currentMessage = inputSky.currentValue;
				
				//trace('on_CLickSendBtn');
				// выполняем отправку в кубик
				//connection = new NetConnection;
				//loginResponder = new Responder(onLoginResult, onLoginFault);
				//messageResponder = new Responder(onResultMessage, onFaultMessage);
				//connection.connect(Qubix.QUBIX_GATEWAY);
				//
				//connection.call("qubix_flash.login", loginResponder, Qubix.QUBIX_LOGIN, Qubix.QUBIX_PASSWORD);
			}
			
		}
		
		private function showMark():void
		{
			inputSky.showMark();
			
			_timeOutDelay = setTimeout(showStamp, 1000);
		}
		
		private function showStamp():void
		{
			inputSky.showStamp();
			
			_timeOutDelay = setTimeout(dalee, 1000);
		}
		
		private function dalee():void
		{
			TweenLite.to(inputSky, 3, { y: -400 , ease:'none', onComplete:OnFinishHideInputSky } );
			
			showSpasibo();
			
			_timeOutDelay = setTimeout(hideSpasibo, 10000);
		}
		
		private function OnFinishHideInputSky():void
		{
			inputSky.y = -400;
			
			bgd.mouseChildren = false;
			bgd.mouseEnabled = false;
			
			
			inputSky.hideMarkaStamp();
			currentText = '';
			
			TweenLite.to(echeBtn, 0.5, { alpha: 1 ,ease:'none'} );
			echeBtn.mouseChildren = true;
			echeBtn.mouseEnabled = true;
			echeBtn.addEventListener(MouseEvent.CLICK, onAddSkyMessage);
			
			
			//inputSky.show(0.5);
			
		}
		
		private function onAddSkyMessage(e:MouseEvent):void 
		{
			////trace('5555555');
			hideSpasibo();
			
			TweenLite.to(echeBtn, 0.5, { alpha: 0 ,ease:'none'} );
			echeBtn.mouseChildren = false;
			echeBtn.mouseEnabled = false;
			
			TweenLite.to(inputSky, 2, {y:INPUT_SKY_FIRST_Y ,ease:'none',onComplete:OnFinishShowInputSky} );
		}
		
		private function OnFinishShowInputSky():void
		{
			board.mouseChildren = true;
			board.mouseEnabled = true;
			setEvents();
		}
		
		private function onClickClearBtn(e:MouseEvent):void 
		{
			currentText = '';
		}
		
		/**
		 * 
		 */
		private function onLoginResult(result:Object):void
		{
			trace('onResult',result);
			var _dataLog:Object = new Object; // заводим новый объект, либо используем уже готовый
			_dataLog = result; // результат делаем глобальным обхектом. Здесь хранятся все данные
			
			//for (var name:String in _dataLog) 
			//{
				//trace('name=',name);
			//}
			
			//connection.call("qubix_flash.send_inmail", messageResponder, { "header": { "content_type":"mes", "subject":_currentName, "to_user_login":"sender", "from_user_login":"demo" }, "categories":"guest", "content": { "content/text/1":_currentmessage }},Main._typelang );
			//trace('+++*++--');
			
			connection.call("qubix_flash.send_inmail", messageResponder, { "header": { "content_type":"mes", "subject":_currentName, "to_user_login":'sender', "from_user_login":"sender" }, "categories":"guest", "content": { "":_currentMessage }}, 'rus' );
			
			
		}
		
		private function onLoginFault(fault:Object):void
		{
			trace('[D:] отправка сообщения, ошибка при логине');
			
		}
		
		private function onResultMessage(result:Object):void
		{
			trace('Сообщение отправлено нормально', result);
			
		}
		
		private function onFaultMessage(fault:Object):void
		{
			trace('[D:] отправка сообщения, ошибка отправки', fault);
			trace('555',fault.faultCode);
			trace('555',fault.faultString);
			trace('555',fault.faultDetail);
			for (var name:String in fault) 
			{
				trace('name = ', name);
			}
			
		}
		
		private function onKeyRight(e:KeyboardEventD):void 
		{
			inputSky.positionCursor = inputSky.currentPositionCursor + 1;
		}
		
		private function onKeyLeft(e:KeyboardEventD):void 
		{
			inputSky.positionCursor = inputSky.currentPositionCursor - 1;
		}
	}

}